<template>
  <div class="app-container">
    <!-- 新增：功能切换按钮 -->
    <el-radio-group v-model="currentFunction" style="margin-bottom: 20px;">
      <el-radio-button label="create">创建订单</el-radio-button>
      <el-radio-button label="detail">查看订单详情</el-radio-button>
    </el-radio-group>

    <!-- 订单详情展示 -->
    <el-card v-if="currentFunction === 'detail'" class="box-card">
      <el-tabs v-model="statusFilter" @tab-click="handleTabClick">
        <el-tab-pane label="待审核" name="1"></el-tab-pane>
        <el-tab-pane label="待服务" name="2"></el-tab-pane>
        <el-tab-pane label="全部" name="all"></el-tab-pane>
      </el-tabs>
      <el-row>
        <el-col :span="8">
          <el-table :data="filteredOrderList" @row-click="row => selectedOrderDetail = row" style="width: 100%">
            <el-table-column prop="orderNo" label="订单号" />
            <el-table-column prop="username" label="用户" />
            <el-table-column prop="employeeName" label="员工" />
          </el-table>
        </el-col>
        <el-col :span="16">
          <el-descriptions :column="2" border v-if="selectedOrderDetail && selectedOrderDetail.orderNo">
            <el-descriptions-item label="订单号">{{ selectedOrderDetail.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="用户">{{ selectedOrderDetail.username }}</el-descriptions-item>
            <el-descriptions-item label="员工">{{ selectedOrderDetail.employeeName }}</el-descriptions-item>
            <el-descriptions-item label="服务地址">{{ selectedOrderDetail.fullAddress }}</el-descriptions-item>
            <el-descriptions-item label="服务内容">{{ selectedOrderDetail.skillNames || selectedOrderDetail.serviceContent }}</el-descriptions-item>
            <el-descriptions-item label="服务类型">{{ selectedOrderDetail.serviceName || selectedOrderDetail.serviceType }}</el-descriptions-item>
            <el-descriptions-item label="上户时间">{{ selectedOrderDetail.homeTime }}</el-descriptions-item>
            <el-descriptions-item label="工作时间">{{ selectedOrderDetail.workTime }}</el-descriptions-item>
            <el-descriptions-item label="最低薪资">
              {{ selectedOrderDetail.priceRangeMin !== undefined && selectedOrderDetail.priceRangeMin !== null ? selectedOrderDetail.priceRangeMin : selectedOrderDetail.price_range_min }}
            </el-descriptions-item>
            <el-descriptions-item label="最高薪资">
              {{ selectedOrderDetail.priceRangeMax !== undefined && selectedOrderDetail.priceRangeMax !== null ? selectedOrderDetail.priceRangeMax : selectedOrderDetail.price_range_max }}
            </el-descriptions-item>
            <el-descriptions-item label="客户特殊需求">{{ selectedOrderDetail.requirements }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ selectedOrderDetail.notes }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">{{ getStatusText(selectedOrderDetail.status) }}</el-descriptions-item>
            <el-descriptions-item label="预约时间">{{ selectedOrderDetail.scheduledTime }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-card>

    <!-- 原有创建订单流程 -->
    <div v-if="currentFunction === 'create'">
      <!-- 步骤条 -->
      <el-steps :active="currentStep" finish-status="success" class="steps-container">
        <el-step title="选择服务类型" description="选择所需服务"></el-step>
        <el-step title="选择服务信息" description="选择服务信息"></el-step>
        <el-step title="填写订单信息" description="填写订单信息"></el-step>
        <el-step title="完成" description="完成"></el-step>
      </el-steps>

      <!-- 步骤1：选择服务类型 -->
      <div v-if="currentStep === 1">
        <el-row :gutter="20">
          <el-col :span="8" v-for="service in serviceList" :key="service.id">
            <el-card class="service-card" @click.native="selectService(service)"
              :class="{ 'selected': selectedService === service.id }" shadow="hover">
              <div class="service-content">
                <h3>{{ service.name }}</h3>
                <p>{{ service.content }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <div class="action-buttons">
          <el-button type="primary" @click="handleNext" :disabled="!selectedService">下一步</el-button>
        </div>
      </div>

      <!-- 步骤2：选择服务信息 -->
      <div v-else-if="currentStep === 2">
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in serviceInfoList" :key="item.id">
            <el-card class="service-card"
              :class="{ selected: selectedServiceInfo && selectedServiceInfo.id === item.id }"
              @click.native="selectServiceInfo(item)" shadow="hover">
              <div>
                <h3>{{ item.serviceName }}</h3>
                <p>服务地址：{{ item.fullAddress }}</p>
                <p>联系人：{{ item.username }}</p>
                <p>联系电话：{{ item.phone }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <div class="action-buttons">
          <el-button @click="currentStep = 1">上一步</el-button>
          <el-button type="primary" :disabled="!selectedServiceInfo" @click="handleNext">下一步</el-button>
        </div>
      </div>

      <!-- 步骤3：填写订单信息 -->
      <div v-else-if="currentStep === 3">
        <el-form :model="orderForm" label-width="120px" class="order-form">
          <el-form-item label="用户">
            <el-select v-model="orderForm.userId" filterable placeholder="请选择用户" @change="handleUserChange">
              <el-option v-for="user in userList" :key="user.id" :label="user.username" :value="user.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="orderForm.contacts" placeholder="请输入联系人" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="orderForm.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="员工">
            <el-select v-model="orderForm.employeeId" placeholder="请选择员工" filterable>
              <el-option v-for="employee in employeeList" :key="employee.id" :label="employee.name" :value="employee.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="服务地址">
            <el-input v-model="orderForm.fullAddress" placeholder="请输入服务地址" readonly>
              <template #append>
                <el-button @click="showMapDialog = true">地图选址</el-button>
              </template>
            </el-input>
          </el-form-item>
          <MapSelector :modelValue="showMapDialog" @update:modelValue="showMapDialog = $event" @select="handleMapSelect" />
          <el-form-item label="服务内容">
            <el-select v-model="orderForm.service_content" multiple collapse-tags placeholder="请选择服务内容">
              <el-option v-for="item in serviceSkills" :key="item.takeid" :label="item.takeSkill" :value="item.takeid" />
            </el-select>
          </el-form-item>
          <el-form-item label="上户时间">
            <el-input v-model="orderForm.home_time" placeholder="请输入上户时间" />
          </el-form-item>
          <el-form-item label="工作时间">
            <el-input v-model="orderForm.work_time" placeholder="请输入工作时间" />
          </el-form-item>
          <el-form-item label="最低薪资">
            <el-input-number v-model="orderForm.price_range_min" :min="0" :step="1000" />
          </el-form-item>
          <el-form-item label="最高薪资">
            <el-input-number v-model="orderForm.price_range_max" :min="0" :step="1000" />
          </el-form-item>
          <el-form-item label="客户特殊需求">
            <el-input v-model="orderForm.requirements" placeholder="请输入客户特殊需求" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="orderForm.notes" type="textarea" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="orderForm.status" placeholder="请选择订单状态">
              <el-option label="审核中" :value="1" />
              <el-option label="待服务" :value="2" />
              <el-option label="服务中" :value="3" />
              <el-option label="已完成" :value="4" />
              <el-option label="已驳回" :value="-1" />
            </el-select>
          </el-form-item>
          <el-form-item label="预约时间">
            <el-date-picker v-model="orderForm.scheduledTime" type="datetime" placeholder="请选择预约时间" />
          </el-form-item>
        </el-form>
        <div class="action-buttons">
          <el-button @click="currentStep = 2">上一步</el-button>
          <el-button type="primary" @click="submitOrder">提交订单</el-button>
        </div>
      </div>

      <!-- 步骤4：完成 -->
      <div v-else-if="currentStep === 4">
        <el-result icon="success" title="订单创建成功" sub-title="您的订单已成功提交！" />
        <div class="action-buttons">
          <el-button type="primary" @click="resetForm">返回首页</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { listOrder2, selectOrderTypeByServiceId, getServiceSkills, insertOrder } from "@/api/order/order2";
import { addAddress } from "@/api/user/address";
import { listEmployee } from "@/api/user/employee";
import { listUserInfo } from "@/api/user/user";
import MapSelector from '@/components/MapSelector/index.vue';

export default {
  name: "OrderService",
  components: {
    MapSelector
  },
  data() {
    return {
      currentFunction: 'create',
      currentStep: 1,
      serviceList: [],
      selectedService: null,
      serviceInfoList: [],
      selectedServiceInfo: null,
      statusFilter: '1',
      orderForm: {
        userId: '',
        employeeId: '',
        addressId: '',
        username: '',
        employeeName: '',
        fullAddress: '',
        contacts: '',
        phone: '',
        service_content: [],
        service_type: '',
        home_time: '',
        work_time: '',
        price_range_min: 0,
        price_range_max: 0,
        requirements: '',
        notes: '',
        status: 1,
        scheduledTime: ''
      },
      serviceSkills: [],
      orderList: [],
      selectedOrderDetail: {},
      employeeList: [],
      userList: [],
      showMapDialog: false
    };
  },
  computed: {
    filteredOrderList() {
      if (this.statusFilter === 'all') {
        return this.orderList;
      }
      return this.orderList.filter(order => String(order.status) === this.statusFilter);
    }
  },
  created() {
    this.getList();
    this.getAllEmployees();
    this.getAllUsers();
  },
  watch: {
    currentFunction(val) {
      if (val === 'detail') {
        if (!this.selectedService) {
          this.$message.warning('请先选择服务类型');
          this.currentFunction = 'create';
          return;
        }
        this.fetchOrderDetail(this.selectedService);
      }
    }
  },
  methods: {
    getList() {
      listOrder2().then(response => {
        this.serviceList = response;
      });
    },
    getAllEmployees() {
      listEmployee().then(response => {
        this.employeeList = response.rows;
      });
    },
    getAllUsers() {
      listUserInfo().then(res => {
        this.userList = res.rows || res;
      });
    },
    selectService(service) {
      this.selectedService = service.id;
      selectOrderTypeByServiceId(service.id).then(res => {
        this.serviceInfoList = res;
        this.selectedServiceInfo = null;
      });
    },
    handleNext() {
      if (this.currentStep === 1 && !this.selectedService) {
        this.$message.warning('请选择服务类型');
        return;
      }
      if (this.currentStep === 2 && !this.selectedServiceInfo) {
        this.$message.warning('请选择服务信息');
        return;
      }
      if (this.currentStep === 2 && this.selectedServiceInfo) {
        this.orderForm = {
          userId: String(this.selectedServiceInfo.userId),
          employeeId: '',
          addressId: String(this.selectedServiceInfo.addressId),
          username: this.selectedServiceInfo.username,
          employeeName: '',
          fullAddress: this.selectedServiceInfo.fullAddress,
          contacts: this.selectedServiceInfo.contacts,
          phone: this.selectedServiceInfo.phone,
          service_content: [],
          service_type: this.selectedService,
          home_time: '',
          work_time: '',
          price_range_min: 0,
          price_range_max: 0,
          requirements: '',
          notes: '',
          status: Number(this.selectedServiceInfo.status) || 1,
          scheduledTime: ''
        };
        this.getServiceSkillsList(this.selectedService);
      }
      this.currentStep++;
    },
    selectServiceInfo(item) {
      this.selectedServiceInfo = item;
    },
    getServiceSkillsList(serviceId) {
      if (!serviceId) return;
      getServiceSkills(serviceId).then(response => {
        const uniqueSkills = [];
        const skillSet = new Set();
        response.forEach(item => {
          if (!skillSet.has(item.takeSkill)) {
            skillSet.add(item.takeSkill);
            uniqueSkills.push(item);
          }
        });
        this.serviceSkills = uniqueSkills;
      });
    },
    async submitOrder() {
      if (!this.orderForm.userId) {
        this.$message.error('请选择用户');
        return;
      }
      if (!this.orderForm.employeeId) {
        this.$message.error('请选择员工');
        return;
      }
      if (!this.orderForm.fullAddress) {
        this.$message.error('请输入服务地址');
        return;
      }
      if (!this.orderForm.service_type) {
        this.$message.error('请选择服务类型');
        return;
      }

      let addressId = this.orderForm.addressId;
      console.log('下单前addressId:', addressId);
      // 判断是否为新地址（没有addressId但有fullAddress）
      if (!addressId && this.orderForm.fullAddress) {
        try {
          const addressPayload = {
            userId: this.orderForm.userId,
            contacts: this.orderForm.contacts,
            phone: this.orderForm.phone,
            fullAddress: this.orderForm.fullAddress,
            addressDetails: this.orderForm.addressDetails || '',
            provinceName: this.orderForm.provinceName || '',
            cityName: this.orderForm.cityName || '',
            districtName: this.orderForm.districtName || '',
            street: this.orderForm.street || '',
            longitude: this.orderForm.longitude || '',
            latitude: this.orderForm.latitude || ''
          };
          console.log('新增地址参数:', addressPayload);
          const addressRes = await addAddress(addressPayload);
          console.log('addAddress返回:', addressRes);
          addressId = addressRes.data.id || addressRes.data;
          this.orderForm.addressId = addressId;
        } catch (e) {
          this.$message.error('新增地址失败');
          return;
        }
      }

      const formData = {
        ...this.orderForm,
        addressId: addressId,
        service_content: Array.isArray(this.orderForm.service_content)
          ? this.orderForm.service_content.join(',')
          : this.orderForm.service_content,
        home_time: this.orderForm.home_time || null,
        work_time: this.orderForm.work_time || null,
        scheduledTime: this.orderForm.scheduledTime instanceof Date
          ? this.orderForm.scheduledTime.toISOString()
          : this.orderForm.scheduledTime || null
      };
      console.log('最终下单参数:', formData);

      insertOrder(formData).then(() => {
        this.currentStep = 4;
      }).catch(error => {
        this.$message.error('订单创建失败: ' + (error.message || '未知错误'));
      });
    },
    resetForm() {
      this.currentStep = 1;
      this.selectedService = null;
      this.selectedServiceInfo = null;
      this.orderForm = {
        userId: '',
        employeeId: '',
        addressId: '',
        username: '',
        employeeName: '',
        fullAddress: '',
        contacts: '',
        phone: '',
        service_content: [],
        service_type: '',
        home_time: '',
        work_time: '',
        price_range_min: 0,
        price_range_max: 0,
        requirements: '',
        notes: '',
        status: 1,
        scheduledTime: ''
      };
      this.serviceSkills = [];
    },
    fetchOrderDetail(serviceId) {
      selectOrderTypeByServiceId(serviceId).then(res => {
        this.orderList = res;
        if (this.filteredOrderList.length > 0) {
          this.selectedOrderDetail = this.filteredOrderList[0];
        } else {
          this.selectedOrderDetail = {};
        }
      });
    },
    getStatusText(status) {
      switch (status) {
        case 1: return '待审核';
        case 2: return '待服务';
        case 3: return '服务中';
        case 4: return '已完成';
        case -1: return '已驳回';
        default: return '未知';
      }
    },
    handleTabClick() {
      if (this.filteredOrderList.length > 0) {
        this.selectedOrderDetail = this.filteredOrderList[0];
      } else {
        this.selectedOrderDetail = {};
      }
    },
    handleMapSelect(val) {
      this.orderForm.fullAddress = val.address;
      this.orderForm.longitude = val.longitude;
      this.orderForm.latitude = val.latitude;
      this.orderForm.addressId = '';
    },
    handleUserChange(userId) {
      const user = this.userList.find(u => u.id === userId);
      if (user) {
        this.orderForm.phone = user.phone || '';
      } else {
        this.orderForm.phone = '';
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.function-select {
  margin-bottom: 20px;
  text-align: center;
}

.steps-container {
  margin-bottom: 30px;
}

.service-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;

  &.selected {
    border: 2px solid #409EFF;
    background-color: #ecf5ff;
    transform: translateY(-5px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);

    .service-content {
      h3 {
        color: #409EFF;
      }
    }
  }

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  }

  .service-content {
    text-align: center;
    padding: 20px;

    h3 {
      margin: 0 0 10px 0;
      color: #303133;
      transition: color 0.3s;
    }

    p {
      margin: 0 0 10px 0;
      color: #606266;
      font-size: 14px;
    }
  }
}

.order-form {
  max-width: 800px;
  margin: 0 auto;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.unit {
  margin-left: 10px;
}

.box-card {
  margin: 20px;
}
</style>
